<template>
    <el-dialog v-model="visible" @close="closePage" :title="title" width="25%">
        <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px" size="large">
            <el-form-item label="岗位编码" prop="code">
                <el-input v-model="formData.code" placeholder="请输入岗位编码" />
            </el-form-item>
            <el-form-item label="岗位名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入岗位名称" />
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" />
            </el-form-item>
        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closePage">取消</el-button>
                <el-button type="primary" @click="addOrUpdate">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { addReq, updateReq } from "@/api/sys/post/index.js"
import { success } from '@/utils/messageUtils.js';
const props = defineProps({
    querySelective: Function,
})

const formRef = ref()
const formData = reactive({
    id: null,
    code: '',
    name: '',
    remark: '',
})

const formRules = {
    code: [{ required: true, message: '请输入岗位编码', trigger: 'blur' }],
    name: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
}

const title = ref()
const isAdd = ref(true)
const visible = ref(false)
const open = (row) => {
    // 重置表单
    formRef.value?.resetFields()
    if (row) {
        title.value = '修改岗位'
        isAdd.value = false

        formData.id = row.id
        formData.code = row.code
        formData.name = row.name
        formData.remark = row.remark
    } else {
        title.value = '添加岗位'
        isAdd.value = true

        formData.id = null
        formData.code = ''
        formData.name = ''
        formData.remark = ''
    }
    visible.value = true;
}

defineExpose({
    open,
})

// 关闭dialog
const closePage = () => {
    visible.value = false;
}

// 修改
const addOrUpdate = () => {
    formRef.value.validate((valid, fields) => {
        if (valid) {
            if (isAdd.value) {
                addReq(formData).then(res => {
                    if (res.code == 200) {
                        success(res.message);
                        props.querySelective();
                        closePage();
                    }
                })
            } else {
                updateReq(formData).then(res => {
                    if (res.code == 200) {
                        success(res.message);
                        props.querySelective();
                        closePage();
                    }
                })
            }
        }
    })
}
</script>